<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FaparentController extends Controller
{

    /**
     * 上下级关系管理
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['a.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['a.me_uid','like',"%{$param['me_uid']}%"];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['a.me_phone','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['me_nick_name']) && !empty($param['me_nick_name'])) {
            $whehe[] = ['a.me_nick_name','like',"%{$param['me_nick_name']}%"];
        }
        $whehetime = '';
        if (isset($param['me_add_time']) && !empty($param['me_add_time'])) {
            $time_arr = explode(' - ', $param['me_add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = "a.me_add_time >= $start_time AND a.me_add_time <= $end_time";
        }

        if (isset($param['fmember_id']) && !empty($param['fmember_id'])) {
            $whehe[] = ['b.member_id','=',$param['fmember_id']];
        }
        if (isset($param['fme_uid']) && !empty($param['fme_uid'])) {
            $whehe[] = ['b.me_uid','like',"%{$param['fme_uid']}%"];
        }
        if (isset($param['fme_phone']) && !empty($param['fme_phone'])) {
            $whehe[] = ['b.me_phone','like',"%{$param['fme_phone']}%"];
        }
        if (isset($param['fme_nick_name']) && !empty($param['fme_nick_name'])) {
            $whehe[] = ['b.me_nick_name','like',"%{$param['fme_nick_name']}%"];
        }
        if (isset($param['is_shi']) && $param['is_shi'] != '') {
            $whehe[] = ['a.me_sex','=',2];
            $whehe[] = ['a.is_shi','=',$param['is_shi']];
        }
        $adminid = $this->uid;

        $Common = New Common();//只能看见自己相关的用户
        $q_member_str = $Common->getMyXmemberIdStr($adminid);
        $wheheShow = '';
        if(!empty($q_member_str)) {
            $wheheShow = "a.member_id in($q_member_str)";
        }

        $order = 'zj_num desc,a.member_id desc';
        if (isset($param['px']) && !empty($param['px'])) {
            switch($param['px']){
                case '1': $order = 'tg_withdrawal desc,a.member_id desc';break;
                case '2': $order = 'dsh_withdrawal desc,a.member_id desc';break;
            }
        }

        $IndexTableModel = New IndexTableModel();
        $data = Db::table('fa_member')
            ->alias('a')
            ->join("fa_member b",'a.me_parent = b.member_id',"LEFT")//父级
            ->join("fa_member_fund c",'a.member_id = c.member_id',"LEFT")//钱包
            ->field("a.*,b.member_id as f_member_id,b.me_uid as f_me_uid,b.me_nick_name as f_me_nick_name,(select count(z.member_id) from fa_member z where z.me_parent=a.member_id) as zj_num,(select sum(t.total_withdrawal) from fa_zwithdrawal_order t where t.member_id = a.member_id and t.status = 0) as dsh_withdrawal,(select sum(tt.total_withdrawal) from fa_zwithdrawal_order tt where tt.member_id = a.member_id and tt.status = 1) as tg_withdrawal,(select sum(cz.pay_money) from fa_recharge_stamp_order cz where cz.member_id = a.member_id) as cz_recharge,a.me_qd,c.stamp_money,c.no_stamp_money")
            ->order($order)
            ->where($whehe)
            ->where($whehetime)
            ->where($wheheShow)
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);

        $data->each(function ($v, $k)use($IndexTableModel,$adminid) {
//            //提现待审核油票
//            $dshwithdrawal = $IndexTableModel->getNum('fa_zwithdrawal_order',"`member_id` = '{$v['member_id']}' and `status` = 0",'total_withdrawal');
//            $v['dsh_withdrawal'] = $dshwithdrawal;
//            //提现通过油票
//            $tgwithdrawal = $IndexTableModel->getNum('fa_zwithdrawal_order',"`member_id` = '{$v['member_id']}' and `status` = 1",'total_withdrawal');
//            $v['tg_withdrawal'] = $tgwithdrawal;
//            //充值金额
//            $czrecharge = $IndexTableModel->getNum('fa_recharge_stamp_order',"`member_id` = '{$v['member_id']}'",'pay_money');
//            $v['cz_recharge'] = $czrecharge;


            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
            }

            $v['dsh_withdrawal'] = !empty($v['dsh_withdrawal'])?$v['dsh_withdrawal']:'0';
            $v['tg_withdrawal'] = !empty($v['tg_withdrawal'])?$v['tg_withdrawal']:'0';
            $v['cz_recharge'] = !empty($v['cz_recharge'])?$v['cz_recharge']:'0';

            if(empty($v['f_member_id'])){
                $v['me_parent_word'] = '未绑定';$v['me_bind_type_word'] = '未绑定';
            }else{
                $v['me_parent_word'] = $v['f_member_id'].'('.$v['f_me_uid'].')('.$v['f_me_nick_name'].')';
                $v['me_bind_type_word'] = '-';
                switch ($v['me_bind_admin']) {
                    case 1:$v['me_bind_type_word'] = '扫码绑定';break;
                    case 2:$v['me_bind_type_word'] = '注册绑定';break;
                    case 3:$v['me_bind_type_word'] = 'VIP绑定';break;
                    case 4:$v['me_bind_type_word'] = '漏绑绑定';break;
                    case 5:$v['me_bind_type_word'] = '后台绑定';break;
                }
            }
            switch($v['me_sex']){
                case '0': $v['me_sex_word'] = '未设置';break;
                case '1': $v['me_sex_word'] = '男';break;
                case '2': $v['me_sex_word'] = '女';break;
            }
            switch($v['me_is_vip']){
                case '0': $v['me_is_vip_word'] = '未开通';break;
                case '1': $v['me_is_vip_word'] = '已开通';break;
            }

            $v['me_status_time_word'] = '-';
            switch($v['me_status']){
                case '1': $v['me_status_word'] = '正常';$v['me_status_time_word'] = '未封禁';break;
                case '2': $v['me_status_word'] = '封禁';
                    if($v['me_status_time'] != -1 && $v['me_status_time'] != 0){
                        $v['me_status_time_word'] = date('Y-m-d H:i:s',$v['me_status_time']);
                    }else{
                        $v['me_status_time_word'] = '永久';
                    }
                    break;
            }

            if(!empty(strpos($v['me_phone'], 'zx'))){
                $v['me_phone'] = explode('zx',$v['me_phone'])[0].'（已注销）';
                $v['me_nick_name'] = explode('zx',$v['me_nick_name'])[0].'（已注销）';
                $v['me_status'] = 99;
                $v['me_status_time_word'] = '已注销';
            }
            $v['me_add_time'] = date('m-d H:i',$v['me_add_time']);
            $v['me_bind_time_word'] = !empty($v['me_bind_time'])?date('m-d H:i',$v['me_bind_time']):'未绑定';
            $v['me_qd_word'] = empty($v['me_qd'])?'-':$v['me_qd'];

            switch($v['is_shi']){
                case '0': $v['is_shi_word'] = '可使用';break;
                case '1': $v['is_shi_word'] = '不可使用';break;
            }
            return $v;
        });
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }


    /**
     * 查看下级
     * User:@hang
     */
    public function getjuniorlist(Request $request)
    {
        $id = input('id');//查看者用户ID
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['b.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['b.me_uid','like',"%{$param['me_uid']}%"];
        }
        if (isset($param['me_phone']) && !empty($param['me_phone'])) {
            $whehe[] = ['b.me_phone','like',"%{$param['me_phone']}%"];
        }
        if (isset($param['me_nick_name']) && !empty($param['me_nick_name'])) {
            $whehe[] = ['b.me_nick_name','like',"%{$param['me_nick_name']}%"];
        }
        $whehetime = '';
        if (isset($param['add_time']) && !empty($param['add_time'])) {
            $time_arr = explode(' - ', $param['add_time']);
            $start_time = strtotime($time_arr[0]);
            $end_time = strtotime($time_arr[1].'23:59:59');
            $whehetime = "a.add_time >= $start_time AND a.add_time <= $end_time";
        }
        if (isset($param['is_shi']) && $param['is_shi'] != '') {
            $whehe[] = ['b.me_sex','=',2];
            $whehe[] = ['b.is_shi','=',$param['is_shi']];
        }

        $order = 'a.add_time desc,zj_num desc';
        if (isset($param['px']) && !empty($param['px'])) {
            switch($param['px']){
                case '1': $order = 'zj_num desc,a.add_time desc';break;
                case '2': $order = 'tg_withdrawal desc,a.add_time desc';break;
                case '3': $order = 'dsh_withdrawal desc,a.add_time desc';break;
                case '4': $order = 'cz_recharge desc,a.add_time desc';break;
                case '5': $order = 'b.me_zx asc,a.add_time desc';break;
            }
        }

//        var_dump($id);
//var_dump($whehetime);die;
        $IndexTableModel = New IndexTableModel();
        $data = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_circle_list c",'b.me_circle_id = c.id',"LEFT")
            ->join("fa_member_fund d",'a.b_member_id = d.member_id',"LEFT")
            ->field("a.*,b.me_zx as z_me_zx,b.member_id as z_member_id,b.me_xn_zx,b.me_add_sort,b.me_uid as z_me_uid,b.me_nick_name as z_me_nick_name,b.me_status as z_me_status,b.me_status_time as z_me_status_time,b.me_phone as z_me_phone,b.me_bind_type as z_me_bind_type,b.me_sex as z_me_sex,b.me_is_vip as z_me_is_vip,b.me_add_time as z_me_add_time,b.is_shi as z_is_shi,c.circle_name,(select count(z.member_id) from fa_member z where z.me_parent=a.b_member_id) as zj_num,(select sum(t.total_withdrawal) from fa_zwithdrawal_order t where t.member_id = a.b_member_id and t.status = 0) as dsh_withdrawal,(select sum(tt.total_withdrawal) from fa_zwithdrawal_order tt where tt.member_id = a.b_member_id and tt.status = 1) as tg_withdrawal,(select sum(cz.pay_money) from fa_recharge_stamp_order cz where cz.member_id = a.b_member_id) as cz_recharge,d.stamp_money,d.no_stamp_money,b.me_bind_admin")
            ->order($order)
            ->where("a.member_id = $id")
            ->where($whehe)
            ->where($whehetime)
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);


        //计算 总在线人数
        $zx_num = Db::table('fa_member')
            ->where("me_parent = $id and me_zx = 0")
            ->count('member_id');
        //计算 总提现待审核油票
        $z_dsh_withdrawal = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_zwithdrawal_order t",'t.member_id = a.b_member_id and t.status = 0',"LEFT")
//            ->join("fa_zwithdrawal_order tt",'tt.member_id = a.b_member_id and tt.status = 1',"LEFT")
//            ->join("fa_recharge_stamp_order cz",'cz.member_id = a.b_member_id',"LEFT")
//            ->field("sum(t.total_withdrawal) as z_dsh_withdrawal,sum(tt.total_withdrawal) as z_tg_withdrawal,sum(cz.pay_money) as z_cz_recharge")
            ->field("sum(t.total_withdrawal) as z_dsh_withdrawal")
            ->where("a.member_id = $id")
            ->where($whehe)
            ->where($whehetime)
            ->find();
        //计算 总提现通过油票
        $z_tg_withdrawal = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_zwithdrawal_order tt",'tt.member_id = a.b_member_id and tt.status = 1',"LEFT")
            ->field("sum(tt.total_withdrawal) as z_tg_withdrawal")
            ->where("a.member_id = $id")
            ->where($whehe)
            ->where($whehetime)
            ->find();
        //计算 总充值金额
        $z_cz_recharge = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_recharge_stamp_order cz",'cz.member_id = a.b_member_id',"LEFT")
            ->field("sum(cz.pay_money) as z_cz_recharge")
            ->where("a.member_id = $id")
            ->where($whehe)
            ->where($whehetime)
            ->find();

        $zTotal['zx_num'] = !empty($zx_num)?$zx_num:'0';
        $zTotal['z_dsh_withdrawal'] = !empty($z_dsh_withdrawal['z_dsh_withdrawal'])?$z_dsh_withdrawal['z_dsh_withdrawal']:'0';
        $zTotal['z_tg_withdrawal'] = !empty($z_tg_withdrawal['z_tg_withdrawal'])?$z_tg_withdrawal['z_tg_withdrawal']:'0';
        $zTotal['z_cz_recharge'] = !empty($z_cz_recharge['z_cz_recharge'])?$z_cz_recharge['z_cz_recharge']:'0';

        $gxArr = $this->getWsjgxMoney($id,'');
        $zTotal['lt_z_gx_money'] = $gxArr['ltGxMoney'];//聊天相关给上级贡献
        $zTotal['cz_z_gx_money'] = $gxArr['czGxMoney'];//会员或充值给上级贡献

        //计算 所有下级聊天总收益
        $total_lt_info = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_finance cw",'cw.member_id = a.b_member_id',"LEFT")
            ->field("sum(cw.money) as total_lt_money")
            ->where("a.member_id = $id and cw.type in (4,5,6) and cw.money_type = 2 and cw.status = 1 and cw.rebate_type = 0 and cw.g_id not in(-99,-88)")
            ->where($whehe)
            ->find();
        $zTotal['total_lt_money'] = !empty($total_lt_info['total_lt_money'])?delete0(bcadd($total_lt_info['total_lt_money'],0,2)):'0';

        //计算 所有下级礼物总收益
        $total_lw_info = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_finance cw",'cw.member_id = a.b_member_id',"LEFT")
            ->field("sum(cw.money) as total_lw_money")
            ->where("a.member_id = $id and cw.type = 13 and cw.money_type = 2 and cw.status = 1 and cw.chat_type = 0 and cw.rebate_type = 0")
            ->where($whehe)
            ->find();
        $zTotal['total_lw_money'] = !empty($total_lw_info['total_lw_money'])?delete0(bcadd($total_lw_info['total_lw_money'],0,2)):'0';

        //计算 所有下级充值总收益
        $total_cz_info = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_finance cw",'cw.member_id = a.b_member_id',"LEFT")
            ->field("sum(cw.money) as total_cz_money")
            ->where("a.member_id = $id and cw.type = 11 and cw.money_type = 2 and cw.status = 1 and cw.chat_type = 0 and cw.rebate_type = 1")
            ->where($whehe)
            ->find();
        $zTotal['total_cz_money'] = !empty($total_cz_info['total_cz_money'])?delete0(bcadd($total_cz_info['total_cz_money'],0,2)):'0';

        //计算 所有下级免费文字收益
        $total_mfwz_info = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_finance cw",'cw.member_id = a.b_member_id',"LEFT")
            ->field("sum(cw.money) as total_mfwz_info")
            ->where("a.member_id = $id and cw.type = 4 and cw.money_type = 2 and cw.status = 1 and cw.rebate_type = 0 and cw.g_id = -88")
            ->where($whehe)
            ->find();
        $zTotal['total_mfwz_info'] = !empty($total_mfwz_info['total_mfwz_info'])?delete0(bcadd($total_mfwz_info['total_mfwz_info'],0,2)):'0';

        //计算 所有下级体验卷收益
        $total_tyj_info = Db::table('fa_member_invite')
            ->alias('a')
            ->join("fa_member b",'a.b_member_id = b.member_id',"LEFT")
            ->join("fa_finance cw",'cw.member_id = a.b_member_id',"LEFT")
            ->field("sum(cw.money) as total_tyj_info")
            ->where("a.member_id = $id and cw.type = 6 and cw.money_type = 2 and cw.status = 1 and cw.rebate_type = 0 and cw.g_id = -99")
            ->where($whehe)
            ->find();
        $zTotal['total_tyj_info'] = !empty($total_tyj_info['total_tyj_info'])?delete0(bcadd($total_tyj_info['total_tyj_info'],0,2)):'0';


//        var_dump($zTotal);die;
        $adminid = $this->uid;
//        $Common = New Common();
//        //此ID用户扫码邀请下级，下级直接进入圈层（多人#号拼接）
//        $tdxjzjjrqcArr = [];
//        $tdxjzjjrqc = $Common->getConfigValue('tdxjzjjrqc');
//        if(!empty($tdxjzjjrqc)){
//            $tdxjzjjrqcArr = explode('#',$tdxjzjjrqc);
//        }

        $data->each(function ($v, $k)use($id,$IndexTableModel,$adminid) {
            //只有超管能看全部手机号
            if($adminid != 1){
                $v['z_me_phone'] = hide_phone_number($v['z_me_phone']);
            }
//            $v['is_smzjjq'] = '-';
//            if(in_array($v['z_member_id'],$tdxjzjjrqcArr)){
//                $v['is_smzjjq'] = '是';
//            }

            $v['dsh_withdrawal'] = !empty($v['dsh_withdrawal'])?$v['dsh_withdrawal']:'0';
            $v['tg_withdrawal'] = !empty($v['tg_withdrawal'])?$v['tg_withdrawal']:'0';
            $v['cz_recharge'] = !empty($v['cz_recharge'])?$v['cz_recharge']:'0';

            $v['z_me_bind_type_word'] = '-';
            switch ($v['me_bind_admin']) {
                case 1:$v['z_me_bind_type_word'] = '扫码绑定';break;
                case 2:$v['z_me_bind_type_word'] = '注册绑定';break;
                case 3:$v['z_me_bind_type_word'] = 'VIP绑定';break;
                case 4:$v['z_me_bind_type_word'] = '漏绑绑定';break;
                case 5:$v['z_me_bind_type_word'] = '后台绑定';break;
            }

            switch($v['z_me_sex']){
                case '0': $v['z_me_sex_word'] = '未设置';break;
                case '1': $v['z_me_sex_word'] = '男';break;
                case '2': $v['z_me_sex_word'] = '女';break;
            }
            switch($v['z_me_is_vip']){
                case '0': $v['z_me_is_vip_word'] = '未开通';break;
                case '1': $v['z_me_is_vip_word'] = '已开通';break;
            }
            switch($v['z_me_zx']){
                case '0': $v['z_me_zx_word'] = '在线';break;
                case '1': $v['z_me_zx_word'] = '离线';break;
            }

            $v['z_me_status_time_word'] = '-';
            switch($v['z_me_status']){
                case '1': $v['z_me_status_word'] = '正常';$v['z_me_status_time_word'] = '未封禁';break;
                case '2': $v['z_me_status_word'] = '封禁';
                    if($v['z_me_status_time'] != -1 && $v['z_me_status_time'] != 0){
                        $v['z_me_status_time_word'] = date('Y-m-d H:i:s',$v['z_me_status_time']);
                    }else{
                        $v['z_me_status_time_word'] = '永久';
                    }
                    break;
            }

            if(!empty(strpos($v['z_me_phone'], 'zx'))){
                $v['z_me_phone'] = explode('zx',$v['z_me_phone'])[0].'（已注销）';
                $v['z_me_nick_name'] = explode('zx',$v['z_me_nick_name'])[0].'（已注销）';
                $v['z_me_status'] = 99;
                $v['z_me_status_time_word'] = '已注销';
            }

            $v['add_time'] = date('m-d H:i',$v['add_time']);
            $v['z_me_add_time'] = date('m-d H:i',$v['z_me_add_time']);
            if($v['status'] == 1){
                $v['status_word'] = '未奖励';
            }else{
                $v['status_word'] = '已奖励';
            }
            $v['jl_time'] = !empty($v['jl_time'])?date('m-d H:i',$v['jl_time']):'-';
            if(empty($v['circle_name'])){
                $v['circle_name_word'] = '未认证';
            }else{
                $v['circle_name_word'] = '已认证'.'('.$v['circle_name'].')';
            }
            switch($v['me_xn_zx']){
                case '0': $v['me_xn_zx_word'] = '是';break;
                case '1': $v['me_xn_zx_word'] = '否';break;
            }
            switch($v['me_add_sort']){
                case '0': $v['me_add_sort_word'] = '否';break;
                case '1': $v['me_add_sort_word'] = '是';break;
            }

            //为上级贡献
            $gxArr = $this->getMembergxMoney($v['z_member_id'],$id,'');
            $v['ltGxMoney'] = $gxArr['ltGxMoney'];
            $v['czGxMoney'] = $gxArr['czGxMoney'];

            switch($v['z_is_shi']){
                case '0': $v['z_is_shi_word'] = '可使用';break;
                case '1': $v['z_is_shi_word'] = '不可使用';break;
            }

            //文字音视频收益
            $v['lt_sy'] = Db::table('fa_finance')->where("`member_id` = '{$v['z_member_id']}' and `type` in(4,5,6) and `money_type` = 2 and `status` = 1 and `rebate_type` = 0 and g_id not in(-99,-88)")->sum('money');
            $v['lt_sy'] = delete0(bcadd($v['lt_sy'],0,2));
            //礼物收益
            $v['lw_sy'] = Db::table('fa_finance')->where("`member_id` = '{$v['z_member_id']}' and `type` = 13 and `money_type` = 2 and `status` = 1 and `chat_type` = 0 and `rebate_type` = 0")->sum('money');
            $v['lw_sy'] = delete0(bcadd($v['lw_sy'],0,2));
            //充值收益
            $v['cz_sy'] = Db::table('fa_finance')->where("`member_id` = '{$v['z_member_id']}' and `type` = 11 and `money_type` = 2 and `status` = 1 and `chat_type` = 0 and `rebate_type` = 1")->sum('money');
            $v['cz_sy'] = delete0(bcadd($v['cz_sy'],0,2));

            //免费文字收益
            $v['mfwz_sy'] = Db::table('fa_finance')->where("`member_id` = '{$v['z_member_id']}' and `type` = 4 and `money_type` = 2 and `status` = 1 and `rebate_type` = 0 and g_id = -88")->sum('money');
            $v['mfwz_sy'] = delete0(bcadd($v['mfwz_sy'],0,2));
            //体验卷收益
            $v['tyj_sy'] = Db::table('fa_finance')->where("`member_id` = '{$v['z_member_id']}' and `type` = 6 and `money_type` = 2 and `status` = 1 and `rebate_type` = 0 and g_id = -99")->sum('money');
            $v['tyj_sy'] = delete0(bcadd($v['tyj_sy'],0,2));

            return $v;
        });

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'fmember_id' => $id,
            'zTotal' => $zTotal,
        ]);
        return $this->fetch();
    }


    /**
     * 计算所有下级为上级贡献油票数
     * $s_membmer_id 受益者上级用户ID
     * $where 筛选条件
     * User:@hang
     */
    public function getWsjgxMoney($s_membmer_id,$where)
    {
        //文字音视频礼物 为上级总贡献
        $ltGxMoney = Db::table('fa_rebate_log')->where("type in (1,2,3,4) and (smember_id = '{$s_membmer_id}' or ssmember_id = '{$s_membmer_id}' or sssmember_id = '{$s_membmer_id}' or ssssmember_id = '{$s_membmer_id}') ".$where)->sum('profit_money');
        $ltGxMoney = delete0(bcadd($ltGxMoney,0,2));
        //充值和VIP 为上级总贡献
        $czGxMoney = Db::table('fa_rebate_log')->where("type in (5,6) and (smember_id = '{$s_membmer_id}' or ssmember_id = '{$s_membmer_id}' or sssmember_id = '{$s_membmer_id}' or ssssmember_id = '{$s_membmer_id}' or czssssmember_id = '{$s_membmer_id}') ".$where)->sum('profit_money');
        $czGxMoney = delete0(bcadd($czGxMoney,0,2));
        return ['ltGxMoney'=>$ltGxMoney,'czGxMoney'=>$czGxMoney];
    }


    /**
     * 计算某单独用户计算为上级贡献油票数
     * $z_member_id 下级用户ID $s_membmer_id 受益者上级用户ID
     * $where 筛选条件
     * User:@hang
     */
    public function getMembergxMoney($z_member_id,$s_membmer_id,$where)
    {
        //文字音视频礼物 为上级总贡献
        $ltGxMoney = Db::table('fa_rebate_log')->where("type in (1,2,3,4) and ((cmember_id = '{$z_member_id}' and smember_id = '{$s_membmer_id}') or (smember_id = '{$z_member_id}' and ssmember_id = '{$s_membmer_id}') or (ssmember_id = '{$z_member_id}' and sssmember_id = '{$s_membmer_id}') or (sssmember_id = '{$z_member_id}' and ssssmember_id = '{$s_membmer_id}')) ".$where)->sum('profit_money');
        $ltGxMoney = delete0(bcadd($ltGxMoney,0,2));
        //充值和VIP 为上级总贡献
        $czGxMoney = Db::table('fa_rebate_log')->where("type in (5,6) and ((cmember_id = '{$z_member_id}' and smember_id = '{$s_membmer_id}') or (smember_id = '{$z_member_id}' and ssmember_id = '{$s_membmer_id}') or (ssmember_id = '{$z_member_id}' and sssmember_id = '{$s_membmer_id}') or (sssmember_id = '{$z_member_id}' and ssssmember_id = '{$s_membmer_id}') or (ssssmember_id = '{$z_member_id}' and czssssmember_id = '{$s_membmer_id}')) ".$where)->sum('profit_money');
        $czGxMoney = delete0(bcadd($czGxMoney,0,2));
        return ['ltGxMoney'=>$ltGxMoney,'czGxMoney'=>$czGxMoney];

//        //文字音视频礼物 为上级贡献
//        $ltGxMoney = Db::table('fa_rebate_log')->where("type in (1,2,3,4) and (cmember_id in($g_member_id_str) or smember_id in($g_member_id_str) or ssmember_id in($g_member_id_str) or sssmember_id in($g_member_id_str)) ".$where)->sum('profit_money');
//        $ltGxMoney = delete0(bcadd($ltGxMoney,0,2));
//        //充值和VIP 为上级贡献
//        $czGxMoney = Db::table('fa_rebate_log')->where("type in (5,6) and grade_type != 1 and (cmember_id in($g_member_id_str) or smember_id in($g_member_id_str) or ssmember_id in($g_member_id_str) or sssmember_id in($g_member_id_str)) ".$where)->sum('profit_money');
//        return ['ltGxMoney'=>$ltGxMoney,'czGxMoney'=>$czGxMoney];
    }



    /**
     * 绑定下级
     * User:@hang
     */
    public function bindsubordinate($id)
    {
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'member_id,me_uid,me_nick_name');
        $this->assign([
            'memberinfo' => $memberInfo,
            'member_id' => $id,
        ]);
        return $this->fetch();
    }


    /**
     * 确定绑定下级
     * User:@hang
     */
    public function actionbindsubordinate()
    {
        $id = input('member_id');
        $me_uid = input('me_uid');//下级用户UID
        if(empty($id)){
            return admin_error('获取上级用户失败',URL_CLOSE_REFRESH);
        }
        if(empty($me_uid)){
            return admin_error('请输入要绑定的下级用户UID或融云ID',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionbindsubordinate'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }
        $IndexTableModel = New IndexTableModel();
        $xInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$me_uid}' or `me_uid` = '{$me_uid}'",'member_id,me_uid,me_bind_type,me_parent,me_nick_name,me_qd');
        if(empty($xInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('未找到符合成为下级的用户',URL_CLOSE_REFRESH);
        }
        if(!empty($xInfo['me_parent'])){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在上级用户',URL_CLOSE_REFRESH);
        }
        $inviteInfo = $IndexTableModel->getFind('fa_member_invite',"`b_member_id` = '{$xInfo['member_id']}'",'id');
        if(!empty($inviteInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在邀请日志',URL_CLOSE_REFRESH);
        }
        if($xInfo['member_id'] == $id){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('您不能将自己绑定为下级',URL_CLOSE_REFRESH);
        }
        if(!empty($xInfo['me_qd'])){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('信息流注册的用户，不可通过此方式绑定为下级',URL_CLOSE_REFRESH);
        }

        $Common = New Common();
        $bkbdnslb = $Common->getConfigValue('bkbdnslb');
        if(!empty($bkbdnslb)){
            $bkbdnslbArr = explode('#',trim($bkbdnslb,'#'));
            if(in_array($xInfo['member_id'],$bkbdnslbArr)){
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('您不能将此用户绑定为下级',URL_CLOSE_REFRESH);
            }
        }

        $ctime = time();
        Db::startTrans();
        $res = $IndexTableModel->editInfo('fa_member',"`member_id` = '{$xInfo['member_id']}'",array('me_bind_type'=>1,'me_parent'=>$id,'me_bind_time'=>$ctime,'me_bind_admin'=>5));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改用户上级信息失败',URL_CLOSE_REFRESH);
        }

        $Common = New Common();
        $sjzdktjlry = $Common->getConfigValue('sjzdktjlry');//上级是此用户时自动打开奖励开关（多人用户ID#号拼接）
        if(!empty($sjzdktjlry)){
            $sjzdktjlryArr = explode('#',$sjzdktjlry);
            if(in_array($id,$sjzdktjlryArr)){
                $IndexTableModel->editInfo('fa_member',"`member_id` = '{$xInfo['member_id']}'",array('me_invitation_rewards'=>1,'me_czlwysp_rewards'=>1));
            }
        }

        $data = array();
        $data['member_id'] = $id;
        $data['b_member_id'] = $xInfo['member_id'];
        $data['me_bind_type'] = 1;
        $data['status'] = 1;
        $data['add_time'] = $ctime;
        $inviteRes = $IndexTableModel->addInfo('fa_member_invite',$data);
        if(empty($inviteRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('邀请日志添加失败',URL_CLOSE_REFRESH);
        }

        //为邀请者添加通知
        $inviteNewRes = $IndexTableModel->addInfo('fa_news_system',array('type'=>7,'member_id'=>$xInfo['member_id'],'j_member_id'=>$id,'g_table'=>'fa_member_invite','g_id'=>$inviteRes,'content'=>'恭喜您，用户【UID：'.$xInfo['me_uid'].'】昵称【'.$xInfo['me_nick_name'].'】，通过【后台绑定】的方式，已经成为您的下级用户。','is_read'=>0,'add_time'=>$ctime));
        if(empty($inviteNewRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('为邀请者添加通知失败',URL_CLOSE_REFRESH);
        }

        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 3;
        $data['member_id'] = $id;
        $data['d_member_id'] = $xInfo['member_id'];
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'member_id,me_uid,me_bind_type,me_parent');
        $data['content'] = '为【'.$memberInfo['member_id'].'】绑定下级用户【'.$xInfo['member_id'].'】';
        $data['add_time'] = $ctime;
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('绑定下级用户成功', URL_RELOAD);
    }



    /**
     * 解绑下级
     * User:@hang
     */
    public function clearparent($id)
    {
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:clearparent'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }
        $IndexTableModel = New IndexTableModel();
        $xInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'member_id,me_uid,me_bind_type,me_parent');
        if(empty($xInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('未查询到下级的用户信息',URL_CLOSE_REFRESH);
        }
        if(empty($xInfo['me_parent'])){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('此下级用户没有上级用户',URL_CLOSE_REFRESH);
        }
        Db::startTrans();
        $res = $IndexTableModel->editInfo('fa_member',"`member_id` = '{$id}'",array('me_bind_type'=>0,'me_parent'=>0,'me_bind_time'=>0,'me_bind_admin'=>0,'is_jiebang'=>1));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('清空上级用户信息失败',URL_CLOSE_REFRESH);
        }
        $IndexTableModel->delOne('fa_member_invite',"`b_member_id` = '{$id}' and `member_id` = '{$xInfo['me_parent']}'");

        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 4;
        $data['member_id'] = $xInfo['me_parent'];
        $data['d_member_id'] = $id;
        $fInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$xInfo['me_parent']}'",'member_id,me_uid,me_bind_type,me_parent');
        $data['content'] = '为【'.$fInfo['member_id'].'】解绑下级用户【'.$xInfo['member_id'].'】';
        $data['add_time'] = time();
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('解绑下级用户成功', URL_RELOAD);
    }



    /**
     * 绑定上级
     * User:@hang
     */
    public function bindparent($id)
    {
        $IndexTableModel = New IndexTableModel();
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$id}'",'member_id,me_uid,me_nick_name');
        $this->assign([
            'memberinfo' => $memberInfo,
            'member_id' => $id,
        ]);
        return $this->fetch();
    }


    /**
     * 确定绑定上级
     * User:@hang
     */
    public function actionbindparent()
    {
        $id = input('member_id');
        $me_uid = input('me_uid');//上级用户UID
        if(empty($id)){
            return admin_error('获取下级用户失败',URL_CLOSE_REFRESH);
        }
        if(empty($me_uid)){
            return admin_error('请输入要绑定的上级用户UID或融云ID',URL_CLOSE_REFRESH);
        }
        //操作上锁
        $Redis_Lock  =  new \Redislock();
        $otc_sell_key  =  'lock:actionbindparent'.$id;	// 定义锁标识
        $is_lock  =  $Redis_Lock->lock($otc_sell_key, 15);	// 获取锁
        //解锁失败
        if(!$is_lock){
            return admin_error('操作频繁，请稍后再试！',URL_CLOSE_REFRESH);
        }
        $IndexTableModel = New IndexTableModel();
        $sInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '{$me_uid}' or `me_uid` = '{$me_uid}'",'member_id,me_uid,me_bind_type,me_parent');
        if(empty($sInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('未找到符合成为上级的用户',URL_CLOSE_REFRESH);
        }
        $memberInfo = $IndexTableModel->getFind('fa_member',"`member_id` = '$id'",'member_id,me_uid,me_bind_type,me_parent,me_nick_name');
        if(empty($memberInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('自身用户信息未查询到',URL_CLOSE_REFRESH);
        }
        if(!empty($memberInfo['me_parent'])){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在上级用户,不可再次绑定上级用户',URL_CLOSE_REFRESH);
        }
        $inviteInfo = $IndexTableModel->getFind('fa_member_invite',"`b_member_id` = '{$memberInfo['member_id']}'",'id');
        if(!empty($inviteInfo)){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('用户已经存在被邀请日志',URL_CLOSE_REFRESH);
        }
        if($sInfo['member_id'] == $id){
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('您不能将自己绑定为上级',URL_CLOSE_REFRESH);
        }

        $Common = New Common();
        $bkbdnslb = $Common->getConfigValue('bkbdnslb');
        if(!empty($bkbdnslb)){
            $bkbdnslbArr = explode('#',trim($bkbdnslb,'#'));
            if(in_array($id,$bkbdnslbArr)){
                $Redis_Lock->unlock($otc_sell_key);	//释放锁
                return admin_error('您不能为此用户绑定上级',URL_CLOSE_REFRESH);
            }
        }

        $ctime = time();
        Db::startTrans();
        $res = $IndexTableModel->editInfo('fa_member',"`member_id` = '{$id}'",array('me_bind_type'=>1,'me_parent'=>$sInfo['member_id'],'me_bind_time'=>$ctime,'me_bind_admin'=>5));
        if(empty($res)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('修改用户上级信息失败',URL_CLOSE_REFRESH);
        }

        $Common = New Common();
        $sjzdktjlry = $Common->getConfigValue('sjzdktjlry');//上级是此用户时自动打开奖励开关（多人用户ID#号拼接）
        if(!empty($sjzdktjlry)){
            $sjzdktjlryArr = explode('#',$sjzdktjlry);
            if(in_array($id,$sjzdktjlryArr)){
                $IndexTableModel->editInfo('fa_member',"`member_id` = '{$id}'",array('me_invitation_rewards'=>1,'me_czlwysp_rewards'=>1));
            }
        }

        $data = array();
        $data['member_id'] = $sInfo['member_id'];
        $data['b_member_id'] = $memberInfo['member_id'];
        $data['me_bind_type'] = 1;
        $data['status'] = 1;
        $data['add_time'] = $ctime;
        $inviteRes = $IndexTableModel->addInfo('fa_member_invite',$data);
        if(empty($inviteRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('邀请日志添加失败',URL_CLOSE_REFRESH);
        }

        //为邀请者添加通知
        $inviteNewRes = $IndexTableModel->addInfo('fa_news_system',array('type'=>7,'member_id'=>$id,'j_member_id'=>$sInfo['member_id'],'g_table'=>'fa_member_invite','g_id'=>$inviteRes,'content'=>'恭喜您，用户【UID：'.$memberInfo['me_uid'].'】昵称【'.$memberInfo['me_nick_name'].'】，通过【后台绑定】的方式，已经成为您的下级用户。','is_read'=>0,'add_time'=>$ctime));
        if(empty($inviteNewRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('为邀请者添加通知失败',URL_CLOSE_REFRESH);
        }

        $data = array();
        $data['user_id'] = $this->uid;
        $data['type'] = 5;
        $data['member_id'] = $id;
        $data['d_member_id'] = $sInfo['member_id'];
        $data['content'] = '为【'.$memberInfo['member_id'].'】绑定上级用户【'.$sInfo['member_id'].'】';
        $data['add_time'] = $ctime;
        $logRes = $IndexTableModel->addInfo('fa_user_operate_log',$data);
        if(empty($logRes)){
            Db::rollBack();
            $Redis_Lock->unlock($otc_sell_key);	//释放锁
            return admin_error('管理端操作日志添加失败',URL_CLOSE_REFRESH);
        }
        Db::commit();
        $Redis_Lock->unlock($otc_sell_key);	//释放锁
        return admin_success('绑定上级用户成功', URL_RELOAD);
    }





}
